from django.contrib import admin

from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.utils.html import format_html
from django.urls import reverse


class LogEntryAdmin(admin.ModelAdmin):
    list_display = ['action_time', 'user', 'content_type', 'object_id', 'object_repr', 'action_flag', 'change_message', 'get_admin_url']
    list_filter = ['action_time', 'user', 'content_type', 'action_flag']
    search_fields = ['user__username', 'object_repr', 'change_message']
    date_hierarchy = 'action_time'
    list_per_page = 20
    readonly_fields = ['action_time', 'user', 'content_type', 'object_id', 'object_repr', 'action_flag', 'change_message']
    ordering = ['-action_time']

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        # 可以根据需要设置是否允许删除日志
        return False

    def get_admin_url(self, obj):
        if obj.content_type and obj.object_id:
            try:
                return format_html(
                    '<a href="{}">查看对象</a>',
                    reverse(
                        f"admin:{obj.content_type.app_label}_{obj.content_type.model}_change",
                        args=(obj.object_id,)
                    )
                )
            except Exception:
                return '链接无效'
        return 'N/A'
    get_admin_url.short_description = '对象链接'


# 注册LogEntry模型到admin站点
admin.site.register(LogEntry, LogEntryAdmin)

# 修改Django Admin的站点标题和页脚
admin.site.site_header = '数据可视化系统管理'
admin.site.site_title = '数据可视化系统管理'
